import React, { useState, useEffect } from 'react';
import styled from 'styled-components';
import { 
  Tabs, 
  Card, 
  Button, 
  Input, 
  Modal, 
  Form, 
  Select, 
  Empty, 
  message,
  Tag,
  Tooltip,
  Space,
  Typography
} from 'antd';
import { 
  FileAddOutlined, 
  SaveOutlined, 
  DeleteOutlined, 
  ShareAltOutlined,
  CloudDownloadOutlined,
  SearchOutlined,
  UserOutlined
} from '@ant-design/icons';
import { 
  TableTemplate, 
  predefinedTemplates, 
  communityTemplates,
  getUserTemplates,
  saveUserTemplate,
  deleteUserTemplate,
  generateId,
  generateThumbnail
} from '../utils/templates';

const { TabPane } = Tabs;
const { Option } = Select;
const { Paragraph } = Typography;

interface TemplateLibraryProps {
  onSelectTemplate: (template: TableTemplate) => void;
  currentTableData: {
    rows: number;
    cols: number;
    cells: any[][];
  };
  onClose: () => void;
}

const LibraryContainer = styled.div`
  width: 100%;
  height: 100%;
  padding: 16px;
  background-color: white;
  border-radius: 4px;
  display: flex;
  flex-direction: column;
`;

const TemplateGrid = styled.div`
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(240px, 1fr));
  gap: 16px;
  margin-top: 16px;
  overflow-y: auto;
  padding-bottom: 16px;
`;

const TemplateCard = styled(Card)<{ $selected?: boolean }>`
  cursor: pointer;
  transition: all 0.3s;
  
  &:hover {
    transform: translateY(-5px);
    box-shadow: 0 4px 12px rgba(0,0,0,0.15);
  }
  
  ${props => props.$selected && `
    border-color: #1890ff;
    box-shadow: 0 0 0 2px rgba(24,144,255,0.2);
  `}
`;

const TemplateImage = styled.div<{ bg: string }>`
  height: 120px;
  background: ${props => props.bg ? `url(${props.bg})` : '#f0f0f0'};
  background-size: cover;
  background-position: center;
  display: flex;
  align-items: center;
  justify-content: center;
  border-radius: 2px;
  margin-bottom: 8px;
  border: 1px solid #f0f0f0;
`;

const CardActions = styled.div`
  margin-top: 8px;
  display: flex;
  justify-content: flex-end;
`;

const SearchBar = styled.div`
  margin-bottom: 16px;
  display: flex;
  gap: 8px;
`;

const CategoryFilter = styled.div`
  margin-bottom: 16px;
  display: flex;
  flex-wrap: wrap;
  gap: 8px;
`;

const TemplateLibrary: React.FC<TemplateLibraryProps> = ({ 
  onSelectTemplate, 
  currentTableData,
  onClose
}) => {
  const [selectedTemplate, setSelectedTemplate] = useState<TableTemplate | null>(null);
  const [userTemplates, setUserTemplates] = useState<TableTemplate[]>([]);
  const [saveModalVisible, setSaveModalVisible] = useState(false);
  const [saveForm] = Form.useForm();
  const [searchText, setSearchText] = useState('');
  const [activeCategory, setActiveCategory] = useState<string>('all');
  
  // 加载用户自定义模板
  useEffect(() => {
    setUserTemplates(getUserTemplates());
  }, []);
  
  // 用于显示的所有模板
  const getFilteredTemplates = (templates: TableTemplate[]): TableTemplate[] => {
    return templates.filter(template => {
      const matchesSearch = !searchText || 
        template.name.toLowerCase().includes(searchText.toLowerCase()) ||
        template.description.toLowerCase().includes(searchText.toLowerCase());
        
      const matchesCategory = activeCategory === 'all' || template.category === activeCategory;
      
      return matchesSearch && matchesCategory;
    });
  };
  
  // 选择模板
  const handleSelectTemplate = (template: TableTemplate) => {
    setSelectedTemplate(template);
  };
  
  // 应用选中的模板
  const handleApplyTemplate = () => {
    if (selectedTemplate) {
      onSelectTemplate(selectedTemplate);
      onClose();
      message.success('模板应用成功！');
    } else {
      message.warning('请先选择一个模板');
    }
  };
  
  // 保存当前表格为新模板
  const showSaveTemplateModal = () => {
    // 预填表单
    saveForm.setFieldsValue({
      name: '',
      description: '',
      category: 'custom'
    });
    
    setSaveModalVisible(true);
  };
  
  // 处理保存模板
  const handleSaveTemplate = (values: any) => {
    const newTemplate: TableTemplate = {
      id: generateId(),
      name: values.name,
      description: values.description,
      category: values.category,
      thumbnail: generateThumbnail(),
      createdAt: Date.now(),
      data: {...currentTableData}
    };
    
    // 保存到本地存储
    saveUserTemplate(newTemplate);
    
    // 更新状态
    setUserTemplates(getUserTemplates());
    
    // 关闭弹窗
    setSaveModalVisible(false);
    message.success('模板保存成功！');
  };
  
  // 删除用户模板
  const handleDeleteTemplate = (templateId: string, e: React.MouseEvent) => {
    e.stopPropagation();
    
    Modal.confirm({
      title: '确认删除',
      content: '您确定要删除这个模板吗？此操作不可恢复。',
      okText: '删除',
      okType: 'danger',
      cancelText: '取消',
      onOk: () => {
        deleteUserTemplate(templateId);
        setUserTemplates(getUserTemplates());
        
        // 如果删除的是当前选中的模板，取消选中
        if (selectedTemplate && selectedTemplate.id === templateId) {
          setSelectedTemplate(null);
        }
        
        message.success('模板已删除');
      }
    });
  };
  
  // 分享到社区（模拟功能）
  const handleShareToCommunity = (template: TableTemplate, e: React.MouseEvent) => {
    e.stopPropagation();
    
    Modal.success({
      title: '分享成功',
      content: '您的模板已成功分享到社区，等待审核后将会显示在社区模板中。',
    });
  };
  
  // 渲染模板卡片
  const renderTemplateCard = (template: TableTemplate, isUserTemplate: boolean = false) => {
    const isSelected = selectedTemplate && selectedTemplate.id === template.id;
    
    return (
      <TemplateCard
        key={template.id}
        $selected={isSelected || false}
        onClick={() => handleSelectTemplate(template)}
        cover={<TemplateImage bg={template.thumbnail} />}
        hoverable
        actions={isUserTemplate ? [
          <Tooltip title="删除">
            <DeleteOutlined onClick={(e) => handleDeleteTemplate(template.id, e)} />
          </Tooltip>,
          <Tooltip title="分享到社区">
            <ShareAltOutlined onClick={(e) => handleShareToCommunity(template, e)} />
          </Tooltip>
        ] : undefined}
      >
        <Card.Meta
          title={template.name}
          description={
            <>
              <Paragraph ellipsis={{ rows: 2 }}>{template.description}</Paragraph>
              {template.createdBy && (
                <div style={{ marginTop: 8 }}>
                  <Tag icon={<UserOutlined />} color="blue">{template.createdBy}</Tag>
                </div>
              )}
              {template.category && (
                <Tag color={
                  template.category === 'resume' ? 'green' :
                  template.category === 'schedule' ? 'blue' :
                  template.category === 'finance' ? 'orange' :
                  template.category === 'community' ? 'purple' : 'default'
                }>
                  {
                    template.category === 'resume' ? '简历' :
                    template.category === 'schedule' ? '课程表' :
                    template.category === 'finance' ? '财务' :
                    template.category === 'community' ? '社区' :
                    template.category === 'custom' ? '自定义' : '其他'
                  }
                </Tag>
              )}
            </>
          }
        />
      </TemplateCard>
    );
  };
  
  // 分类过滤器选项
  const categories = [
    { value: 'all', label: '全部', color: '' },
    { value: 'resume', label: '简历', color: 'green' },
    { value: 'schedule', label: '课程表', color: 'blue' },
    { value: 'finance', label: '财务', color: 'orange' },
    { value: 'custom', label: '自定义', color: 'cyan' },
    { value: 'community', label: '社区', color: 'purple' }
  ];
  
  return (
    <LibraryContainer>
      <Tabs defaultActiveKey="predefined">
        <TabPane tab="预设模板" key="predefined">
          <SearchBar>
            <Input
              placeholder="搜索模板..."
              prefix={<SearchOutlined />}
              onChange={(e) => setSearchText(e.target.value)}
              value={searchText}
              style={{ width: 250 }}
            />
          </SearchBar>
          
          <CategoryFilter>
            {categories.filter(c => c.value !== 'community' && c.value !== 'custom').map(category => (
              <Tag 
                key={category.value}
                color={activeCategory === category.value ? (category.color || 'blue') : ''}
                style={{ cursor: 'pointer', padding: '5px 10px' }}
                onClick={() => setActiveCategory(category.value)}
              >
                {category.label}
              </Tag>
            ))}
          </CategoryFilter>
          
          <TemplateGrid>
            {getFilteredTemplates(predefinedTemplates).length > 0 ? (
              getFilteredTemplates(predefinedTemplates).map(template => renderTemplateCard(template))
            ) : (
              <Empty description="没有找到匹配的模板" />
            )}
          </TemplateGrid>
        </TabPane>
        
        <TabPane tab="我的模板" key="custom">
          <Space style={{ marginBottom: 16 }}>
            <Button 
              type="primary" 
              icon={<SaveOutlined />}
              onClick={showSaveTemplateModal}
            >
              保存当前表格为模板
            </Button>
            
            <Input
              placeholder="搜索我的模板..."
              prefix={<SearchOutlined />}
              onChange={(e) => setSearchText(e.target.value)}
              value={searchText}
              style={{ width: 250 }}
            />
          </Space>
          
          <TemplateGrid>
            {userTemplates.length > 0 ? (
              getFilteredTemplates(userTemplates).map(template => 
                renderTemplateCard(template, true)
              )
            ) : (
              <Empty 
                description="您还没有保存任何自定义模板" 
                image={Empty.PRESENTED_IMAGE_SIMPLE}
              >
                <Button 
                  type="primary" 
                  icon={<SaveOutlined />}
                  onClick={showSaveTemplateModal}
                >
                  创建第一个模板
                </Button>
              </Empty>
            )}
          </TemplateGrid>
        </TabPane>
        
        <TabPane tab="社区模板" key="community">
          <SearchBar>
            <Input
              placeholder="搜索社区模板..."
              prefix={<SearchOutlined />}
              onChange={(e) => setSearchText(e.target.value)}
              value={searchText}
              style={{ width: 250 }}
            />
          </SearchBar>
          
          <TemplateGrid>
            {getFilteredTemplates(communityTemplates).length > 0 ? (
              getFilteredTemplates(communityTemplates).map(template => renderTemplateCard(template))
            ) : (
              <Empty description="没有找到匹配的社区模板" />
            )}
          </TemplateGrid>
        </TabPane>
      </Tabs>
      
      <div style={{ marginTop: 'auto', display: 'flex', justifyContent: 'flex-end', paddingTop: 16, borderTop: '1px solid #f0f0f0' }}>
        <Space>
          <Button onClick={onClose}>取消</Button>
          <Button 
            type="primary" 
            disabled={!selectedTemplate}
            onClick={handleApplyTemplate}
            icon={<CloudDownloadOutlined />}
          >
            应用选中模板
          </Button>
        </Space>
      </div>
      
      {/* 保存模板表单 */}
      <Modal
        title="保存为模板"
        visible={saveModalVisible}
        onCancel={() => setSaveModalVisible(false)}
        footer={null}
      >
        <Form
          form={saveForm}
          layout="vertical"
          onFinish={handleSaveTemplate}
        >
          <Form.Item
            name="name"
            label="模板名称"
            rules={[{ required: true, message: '请输入模板名称' }]}
          >
            <Input placeholder="给您的模板起个名字" />
          </Form.Item>
          
          <Form.Item
            name="description"
            label="模板描述"
            rules={[{ required: true, message: '请输入模板描述' }]}
          >
            <Input.TextArea 
              placeholder="简要描述一下这个模板的用途" 
              rows={3}
            />
          </Form.Item>
          
          <Form.Item
            name="category"
            label="分类"
            rules={[{ required: true, message: '请选择分类' }]}
          >
            <Select>
              <Option value="resume">简历</Option>
              <Option value="schedule">课程表</Option>
              <Option value="finance">财务</Option>
              <Option value="custom">自定义</Option>
            </Select>
          </Form.Item>
          
          <Form.Item>
            <div style={{ display: 'flex', justifyContent: 'flex-end' }}>
              <Space>
                <Button onClick={() => setSaveModalVisible(false)}>
                  取消
                </Button>
                <Button type="primary" htmlType="submit" icon={<SaveOutlined />}>
                  保存
                </Button>
              </Space>
            </div>
          </Form.Item>
        </Form>
      </Modal>
    </LibraryContainer>
  );
};

export default TemplateLibrary; 